package com.xinchuang.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.xinchuang.comment.R;
import com.xinchuang.common.KeyWordSystem;
import com.xinchuang.common.Result;
import com.xinchuang.common.ResultUtil;
import com.xinchuang.entity.elseParam.Ele;
import com.xinchuang.entity.elseParam.Element;
import com.xinchuang.entity.repacigi.RepacigiBaseTable;
import com.xinchuang.entity.repacigi.RepacigiMainTable;
import com.xinchuang.entity.repacigi.RepacigiSubTable;
import com.xinchuang.entity.target.TargetBaseData;
import com.xinchuang.entity.target.TargetPositon;
import com.xinchuang.entity.targetSystem.external.ExternalTarget;
import com.xinchuang.entity.targetSystem.system.CommonAttribute;
import com.xinchuang.entity.targetSystem.system.PostureType;
import com.xinchuang.entity.targetSystem.system.TargetSubType;
import com.xinchuang.entity.targetSystem.system.TargetType;
import com.xinchuang.entity.targetSystem.target.SystemIndex;
import com.xinchuang.entity.targetSystem.target.TargetData;
import com.xinchuang.mapper.repacigi.RepacigiMainTableMapper;
import com.xinchuang.mapper.repacigi.RepacigiSubTableMapper;
import com.xinchuang.mapper.target.TargetBaseDataMapper;
import com.xinchuang.mapper.target.TargetSpecialAttributeMapper;
import com.xinchuang.mapper.target.TargetSubBaseTableMapper;
import com.xinchuang.mapper.targetSystem.CommonMapper;
import com.xinchuang.mapper.targetSystem.TargetMapper;
import com.xinchuang.mapper.targetSystem.TargetSubTypeMapper;
import com.xinchuang.mapper.targetSystem.TargetTypeMapper;
import com.xinchuang.mapper.targetSystem.external.TargetExternalMapper;
import com.xinchuang.service.AchievementService;
import com.xinchuang.service.RedisUseService;
import com.xinchuang.service.elses.EleService;
import com.xinchuang.service.elses.ElementService;
import com.xinchuang.service.repacigi.RepacigiBaseTableService;
import com.xinchuang.service.repacigi.RepacigiMainTableService;
import com.xinchuang.service.repacigi.RepacigiSubTableService;
import com.xinchuang.service.target.TargetPositonService;
import com.xinchuang.service.targetSystem.TargetService;
import com.xinchuang.service.targetSystem.TargetSubTypeService;
import com.xinchuang.service.targetSystem.TargetTypeService;
import com.xinchuang.service.targetSystem.target.PostureTypeService;
import com.xinchuang.service.targetSystem.target.SystemIndexService;
import com.xinchuang.sqlite.TargetRepo;
import com.xinchuang.util.FileElseUtil;
import com.xinchuang.util.RedisUtil;
import com.xinchuang.util.SnowflakeIdWorker;
import com.xinchuang.utils.ObjectUtil;
import com.xinchuang.utils.RedisName;
import com.xinchuang.utils.WordUtils;
import fr.opensagres.xdocreport.document.IXDocReport;
import fr.opensagres.xdocreport.document.images.FileImageProvider;
import fr.opensagres.xdocreport.document.images.IImageProvider;
import fr.opensagres.xdocreport.document.registry.XDocReportRegistry;
import fr.opensagres.xdocreport.template.IContext;
import fr.opensagres.xdocreport.template.TemplateEngineKind;
import fr.opensagres.xdocreport.template.formatter.FieldsMetadata;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.*;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author zkwczx
 */
@Service
public class AchievementServiceImpl implements AchievementService {

    @Resource
    private TargetBaseDataMapper targetBaseDataMapper;

    @Resource
    private TargetSpecialAttributeMapper targetSpecialAttributeMapper;

    @Resource
    private TargetSubBaseTableMapper targetSubBaseTableMapper;

    @Resource
    private TargetSubTypeService targetSubTypeService;

    @Resource
    private TargetTypeMapper targetTypeMapper;

    @Resource
    private TargetMapper targetMapper;

    @Resource
    private TargetExternalMapper target;

    private TargetRepo repo = new TargetRepo();

    @Resource
    private KeyWordSystem keyWordSystem;

    @Resource
    private RepacigiBaseTableService repacigiBaseTableService;

    @Resource
    private RepacigiMainTableMapper repacigiMainTableMapper;

    @Resource
    private RepacigiSubTableMapper repacigiSubTableMapper;

    @Resource
    private RepacigiMainTableService repacigiMainTableService;

    @Resource
    private RepacigiSubTableService repacigiSubTableService;

    @Resource
    private EleService eleService;

    @Resource
    private ElementService elementService;

    @Resource
    private TargetService targetService;

    private SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(1, 1);

    @Resource
    private CommonMapper commonMapper;

    @Resource
    private TargetPositonService targetPositonService;

    @Resource
    private TargetTypeService targetTypeService;

    @Resource
    private PostureTypeService postureTypeService;

    @Resource
    private RedisUseService redisUseService;

    @Resource
    private SystemIndexService systemIndexService;

    @Resource
    private TargetSubTypeMapper targetSubTypeMapper;

    @Resource
    private RedisUtil redisUtil;

    private TargetRepo targetRepo = new TargetRepo();

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public String addResultWord(JSONObject jsonObject) {
        //目标ID
        String tarId = jsonObject.getString("tarId");
        //文件地址
        String fileUrl = jsonObject.getString("fileUrl");
        File file = FileUtil.newFile(keyWordSystem.getFILE_URL() + fileUrl);
        if (!file.isFile() || file.length() < 0) {
            return JSON.toJSONString(R.fail("文件不存在，请重新上传"));
        }


        return JSON.toJSONString(R.success("无数据"));
    }

    @Override
    public String tarAttribute(JSONObject jsonObject) {
        //jsonobject解析获取标识
        String tarId = jsonObject.getString("tarId");
        RepacigiMainTable repacigiMainTable = repacigiMainTableMapper.selectById(tarId);
        if (cn.hutool.core.util.ObjectUtil.isNotEmpty(repacigiMainTable)) {
            return JSON.toJSONString(R.data(repacigiMainTable));
        }
        return JSON.toJSONString(R.success("无数据"));
    }

    @Override
    public Result tarAttributeEdit(JSONObject jsonObject) {
        //jsonobject解析获取标识
        String tarId = jsonObject.getString("tarId");
        //jsonobject解析获取MB标识
        String tarSign = jsonObject.getString("tarSign");
        //jsonobject解析获取MB识别码
        String tarCode = jsonObject.getString("tarCode");
        //jsonobject解析获取国家地区
        String country = jsonObject.getString("country");
        //jsonobject解析获取MB区
        String tarRegion = jsonObject.getString("tarRegion");
        //jsonobject解析获取MB名称
        String tarName = jsonObject.getString("tarName");
        //jsonobject解析获取MB编号
        String tarSerial = jsonObject.getString("tarSerial");
        //jsonobject解析获取类别
        String tarType = jsonObject.getString("tarType");
        //jsonobject解析获取MB等级
        String tarGradient = jsonObject.getString("tarGradient");
        //jsonobject解析获取成果可信度
        String tarReliability = jsonObject.getString("tarReliability");
        //jsonobject解析获取坐标系
        String coordinateSystem = jsonObject.getString("coordinateSystem");
        //jsonobject解析获取定位点子MB
        String subPosition = jsonObject.getString("subPosition");
        //jsonobject解析获取定位点
        String position = jsonObject.getString("position");
        //jsonobject解析获取经度（度分秒）
        String lon = jsonObject.getString("lon");
        //jsonobject解析获取纬度（度分秒）
        String lat = jsonObject.getString("lat");
        //jsonobject解析获取大地高度（米）
        String geoHeight = jsonObject.getString("geoHeight");
        //jsonobject解析获取海拔高度（米）
        String altitude = jsonObject.getString("altitude");
        //jsonobject解析获取面积（平方米）
        String area = jsonObject.getString("area");
        //jsonobject解析获取备注
        String remark = jsonObject.getString("remark");
        //jsonobject解析获取点位误差（米）
        String pointError = jsonObject.getString("pointError");
        //jsonobject解析获取经度误差（秒）
        String lonError = jsonObject.getString("lonError");
        //jsonobject解析获取纬度误差（秒）
        String latError = jsonObject.getString("latError");
        //jsonobject解析获取大地高误差（米）
        String geoHeightError = jsonObject.getString("geoHeightError");
        //jsonobject解析获取海拔高误差（米）
        String altitudeError = jsonObject.getString("altitudeError");
        //jsonobject解析获取原图误差（米）
        String masterMapError = jsonObject.getString("masterMapError");
        //jsonobject解析获取图制作误差（米）
        String tarMapError = jsonObject.getString("tarMapError");
        //jsonobject解析获取地物加绘误差（米）
        String plotError = jsonObject.getString("plotError");
        //jsonobject解析获取成果密级
        String resultClassification = jsonObject.getString("resultClassification");
        //jsonobject解析获取整编单位
        String reorganizeUnit = jsonObject.getString("reorganizeUnit");
        //jsonobject解析获取整编日期
        String reorganizeDate = jsonObject.getString("reorganizeDate");
        //jsonobject解析获取出版序号
        String publicationNumber = jsonObject.getString("publicationNumber");
        RepacigiMainTable build = RepacigiMainTable.builder().tarId(tarId).tarSign(tarSign).tarCode(tarCode)
                .country(country).tarRegion(tarRegion).tarName(tarName).tarSerial(tarSerial)
                .tarType(tarType).tarGradient(tarGradient).tarReliability(tarReliability)
                .coordinateSystem(coordinateSystem).subPosition(subPosition).position(position)
                .lon(lon).lat(lat).geoHeight(geoHeight).altitude(altitude).area(area)
                .remark(remark).pointError(pointError).lonError(lonError).latError(latError)
                .geoHeightError(geoHeightError).altitudeError(altitudeError).masterMapError(masterMapError)
                .tarMapError(tarMapError).plotError(plotError).resultClassification(resultClassification)
                .reorganizeUnit(reorganizeUnit).reorganizeDate(reorganizeDate).publicationNumber(publicationNumber)
                .build();
        repacigiMainTableService.saveOrUpdate(build);
        repacigiBaseTableService.lambdaUpdate().set(RepacigiBaseTable::getTypeName, tarName)
                .eq(RepacigiBaseTable::getTypeId, tarId).update();
        return ResultUtil.success("更新成功");
    }

    @Override
    public String subAttribute(JSONObject jsonObject) {
        //jsonobject解析获取标识
        String subId = jsonObject.getString("subId");
        RepacigiSubTable repacigiSubTable = repacigiSubTableMapper.selectById(subId);
        if (cn.hutool.core.util.ObjectUtil.isNotEmpty(repacigiSubTable)) {
            return JSON.toJSONString(R.data(repacigiSubTable));
        }
        return JSON.toJSONString(R.success("无数据"));
    }

    @Override
    public Result subAttributeEdit(JSONObject jsonObject) {
        //jsonobject解析获取标识
        String subId = jsonObject.getString("subId");
        //jsonobject解析获取标识
        String targetId = jsonObject.getString("targetId");
        //jsonobject解析获取子MB标识
        String subSign = jsonObject.getString("subSign");
        //jsonobject解析获取名称
        String subName = jsonObject.getString("subName");
        //jsonobject解析获取标识码
        String subCode = jsonObject.getString("subCode");
        //jsonobject解析获取类型
        String subType = jsonObject.getString("subType");
        //jsonobject解析获取材质类型
        String materialType = jsonObject.getString("materialType");
        //jsonobject解析获取结构类型
        String structureType = jsonObject.getString("structureType");
        //jsonobject解析获取长度（米）
        String length = jsonObject.getString("length");
        //jsonobject解析获取宽度（米）
        String wide = jsonObject.getString("wide");
        //jsonobject解析获取高度（米）
        String height = jsonObject.getString("height");
        //jsonobject解析获取方位角（度）
        String azimuthAngle = jsonObject.getString("azimuthAngle");
        //jsonobject解析获取圆内半径（米）
        String inRadius = jsonObject.getString("inRadius");
        //jsonobject解析获取圆外半径（米）
        String outRadius = jsonObject.getString("outRadius");
        //jsonobject解析获取坐标系
        String coordinateSystem = jsonObject.getString("coordinateSystem");
        //jsonobject解析获取定位点
        String position = jsonObject.getString("position");
        //jsonobject解析获取经度（度分秒）
        String lon = jsonObject.getString("lon");
        //jsonobject解析获取纬度（度分秒）
        String lat = jsonObject.getString("lat");
        //jsonobject解析获取大地高度（米）
        String geoHeight = jsonObject.getString("geoHeight");
        //jsonobject解析获取海拔高度（米）
        String altitude = jsonObject.getString("altitude");
        //jsonobject解析获取面积（平方米）
        String area = jsonObject.getString("area");
        //jsonobject解析获取备注
        String remark = jsonObject.getString("remark");
        //jsonobject解析获取点位误差（米）
        String pointError = jsonObject.getString("pointError");
        //jsonobject解析获取经度误差（秒）
        String lonError = jsonObject.getString("lonError");
        //jsonobject解析获取纬度误差（秒）
        String latError = jsonObject.getString("latError");
        //jsonobject解析获取大地高误差（米）
        String geoHeightError = jsonObject.getString("geoHeightError");
        //jsonobject解析获取海拔高误差（米）
        String altitudeError = jsonObject.getString("altitudeError");
        //jsonobject解析获取原图误差（米）
        String masterMapError = jsonObject.getString("masterMapError");
        //jsonobject解析获取图制作误差（米）
        String tarMapError = jsonObject.getString("tarMapError");
        //jsonobject解析获取地物加绘误差（米）
        String plotError = jsonObject.getString("plotError");
        String shapeType = jsonObject.getString("shapeType");
        RepacigiSubTable build = RepacigiSubTable.builder().subId(subId).targetId(targetId).subSign(subSign)
                .subName(subName).subCode(subCode).subType(subType).materialType(materialType)
                .structureType(structureType).length(length).wide(wide).height(height)
                .azimuthAngle(azimuthAngle).inRadius(inRadius).outRadius(outRadius)
                .coordinateSystem(coordinateSystem).position(position).lon(lon)
                .lat(lat).geoHeight(geoHeight).altitude(altitude).area(area)
                .remark(remark).pointError(pointError).lonError(lonError).latError(latError)
                .geoHeightError(geoHeightError).altitudeError(altitudeError)
                .masterMapError(masterMapError).tarMapError(tarMapError)
                .plotError(plotError).shapeType(shapeType).build();
        repacigiSubTableService.saveOrUpdate(build);
        return ResultUtil.success("更新成功", null);
    }

    @Override
    public String element(JSONObject jsonObject) {
        //jsonobject解析获取标识
        String tarId = jsonObject.getString("tarId");
        //jsonobject解析获取标识
        String eleId = jsonObject.getString("eleId");
        Element one = elementService.getOne(new LambdaQueryWrapper<Element>().eq(Element::getTargetId, tarId).eq(Element::getElementId, eleId));
        String value = "";
        if (cn.hutool.core.util.ObjectUtil.isNotNull(one)) {
            value = one.getElementValue();
        }
        JSONObject json = new JSONObject();
        json.put("eleContent", value);
        return JSON.toJSONString(R.data(json));
    }

    @Override
    public String elementEdit(JSONObject jsonObject) {
        //jsonobject解析获取标识
        String tarId = jsonObject.getString("tarId");
        //jsonobject解析获取标识
        String eleId = jsonObject.getString("eleId");
        //jsonobject解析获取要素内容
        String eleContent = jsonObject.getString("eleContent");
        Element one = elementService.getOne(new LambdaQueryWrapper<Element>().eq(Element::getTargetId, tarId).eq(Element::getElementId, eleId));
        String value = "";
        if (cn.hutool.core.util.ObjectUtil.isNull(one)) {
            one = new Element();
            one.setTargetId(tarId);
            one.setElementId(eleId);
        }
        one.setElementValue(eleContent);
        elementService.saveOrUpdate(one);
        return JSON.toJSONString(R.success("编辑成功"));
    }

    @Override
    public String exportResult(JSONObject jsonObject) {
        //标识
        String tarId = jsonObject.getString("tarId");
        TargetBaseData baseData = targetBaseDataMapper.selectById(tarId);
        if (ObjectUtil.isEmpty(baseData)) {
            return JSON.toJSONString(R.fail("mb信息不存在"));
        }
        RepacigiMainTable repacigiMainTable = repacigiMainTableService.getById(tarId);

        try {
            FileUtil.mkdir(keyWordSystem.getFILE_URL() + "/file/achievement");
            String time = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN);
            InputStream ins = this.getClass().getResourceAsStream("/成果模板.docx");
            if (null == ins) {
                return JSON.toJSONString(R.fail("模板异常，请重试"));
            }
            IXDocReport report = XDocReportRegistry.getRegistry().loadReport(ins, TemplateEngineKind.Freemarker);
            FieldsMetadata fieldsMetadata = report.createFieldsMetadata();
            IContext context = report.createContext();
            // 创建要替换的文本变量
            context.put("specialName", "MB成果");
            context.put("overview", "");

            context.put("country", StringUtils.isBlank(repacigiMainTable.getCountry()) ? "" : repacigiMainTable.getCountry());
            context.put("tarRegion", StringUtils.isBlank(repacigiMainTable.getTarRegion()) ? "" : repacigiMainTable.getTarRegion());
            context.put("tarName", StringUtils.isBlank(repacigiMainTable.getTarName()) ? "" : repacigiMainTable.getTarName());
            context.put("tarSerial", StringUtils.isBlank(repacigiMainTable.getTarSerial()) ? "" : repacigiMainTable.getTarSerial());
            context.put("tarGradient", StringUtils.isBlank(repacigiMainTable.getTarGradient()) ? "" : repacigiMainTable.getTarGradient());
            String tarType = "";
            if (StringUtils.isNotBlank(repacigiMainTable.getTarType())) {
                TargetType targetType = targetTypeMapper.selectTypeOnly(repacigiMainTable.getTarType());
                if (cn.hutool.core.util.ObjectUtil.isNotEmpty(targetType)) {
                    tarType = targetType.getTypeName();
                }
            }
            context.put("tarType", tarType);
            context.put("subPosition", StringUtils.isBlank(repacigiMainTable.getSubPosition()) ? "" : repacigiMainTable.getSubPosition());
            context.put("coordinateSystem", StringUtils.isBlank(repacigiMainTable.getCoordinateSystem()) ? "" : repacigiMainTable.getCoordinateSystem());
            context.put("lon", StringUtils.isBlank(repacigiMainTable.getLon()) ? "" : repacigiMainTable.getLon());
            context.put("lat", StringUtils.isBlank(repacigiMainTable.getLat()) ? "" : repacigiMainTable.getLat());
            context.put("geoHeight", StringUtils.isBlank(repacigiMainTable.getGeoHeight()) ? "" : repacigiMainTable.getGeoHeight());
            context.put("altitude", StringUtils.isBlank(repacigiMainTable.getAltitude()) ? "" : repacigiMainTable.getAltitude());
            context.put("reorganizeDate", StringUtils.isBlank(repacigiMainTable.getReorganizeDate()) ? "" : repacigiMainTable.getReorganizeDate());
            context.put("reorganizeUnit", StringUtils.isBlank(repacigiMainTable.getReorganizeUnit()) ? "" : repacigiMainTable.getReorganizeUnit());
            //
            fieldsMetadata.addFieldAsImage("imageData");
            IImageProvider imageProvider = new FileImageProvider(new File(keyWordSystem.getFILE_URL() + "/file/achievement/" + time + ".png"));
            context.put("imageData", imageProvider);
            report.setFieldsMetadata(fieldsMetadata);
            // 输出到本地目录
            String fileName = repacigiMainTable.getTarName() + "_MB成果_" + time;
            String storePath = keyWordSystem.getFILE_URL() + "/file/achievement/" + fileName + ".docx";
            File file = new File(storePath);
            FileOutputStream out = new FileOutputStream(file);
            report.process(context, out);
//            // 查询子目标
            List<RepacigiSubTable> repacigiSubTables = repacigiSubTableService
                    .lambdaQuery()
                    .eq(RepacigiSubTable::getTargetId, tarId)
                    .list();

            //复制表格
            WordUtils.copyTableByLoop2(storePath, 2, repacigiSubTables.size() - 1, storePath);
            //表格赋值
            WordUtils.setTableValue(storePath, repacigiSubTables);

//        FileTable fileTable = new FileTable();
//        fileTable.setName(FileUtil.getName(fileName));
//        fileTable.setFileSize(String.valueOf(file.length()));
//        fileTable.setType("docx");
//        fileTable.setFileUrl(file.getAbsolutePath());
//        fileTable.setFileId(IdUtil.simpleUUID());
//        fileTable.setRelId(IdUtil.simpleUUID());
//        fileTable.setCreateTime(LocalDateTime.now());
//        fileTable.setUpdateTime(LocalDateTime.now());
            // todo:添加人
//        fileTableService.save(fileTable);

            JSONObject json = new JSONObject();
            json.put("fileUrl", "/file/special/" + fileName + ".docx");
            json.put("fileName", fileName + ".docx");
            return JSON.toJSONString(R.data(json, "导出成功"));
        } catch (Exception e) {
            return JSON.toJSONString(R.fail("模板异常，请重试"));
        }

//        List<MbPropertyInfo> mainInfo = targetSpecialAttributeMapper.getMainTableInfo(tarId, baseData.getTargetClassify());
//        Map<String, String> mainMap = mainInfo.stream().collect(Collectors.toMap(MbPropertyInfo::getName, MbPropertyInfo::getValue));
//        ResultsTemplate template = ResultsTemplate.builder()
//                .country(mainTable.getCountry())
//                .mbArea(mainTable.getTarRegion())
//                .mbName(mainTable.getTarName())
//                .mbNum(mainTable.getTarSerial())
//                .mbClass(mainTable.getTarGradient())
//                .mbType(mainTable.getTarType())
//                .subMb(mainTable.getSubPosition())
//                .coordinate(mainTable.getCoordinateSystem())
//                .longitude(mainTable.getLon())
//                .latitude(mainTable.getLat())
//                .earthHeight(mainTable.getGeoHeight())
//                .altitude(mainTable.getAltitude())
//                .unit(mainTable.getReorganizeUnit())
//                .subTile("")
//                .build();
//                .country(mainMap.get("国家地区"))
//                .mbArea(mainMap.get("MB区"))
//                .mbName(mainMap.get("MB名称"))
//                .mbNum(mainMap.get("MB编号"))
//                .mbClass(mainMap.get("MB等级"))
//                .mbType(mainMap.get("MB类型"))
//                .subMb(mainMap.get("定位点子MB"))
//                .coordinate(mainMap.get("坐标体系"))
//                .longitude(mainMap.get("经度"))
//                .latitude(mainMap.get("纬度"))
//                .earthHeight(mainMap.get("大地高"))
//                .altitude(mainMap.get("海拔高"))
//                .unit(mainMap.get("整编单位 "))
//                .subTile(mainMap.get("MB名称"))
//                .build();
//        List<TargetSubBaseTable> subBaseTables = targetSubBaseTableMapper.selectList(
//                new LambdaQueryWrapper<TargetSubBaseTable>()
//                        .eq(TargetSubBaseTable::getTargetId, tarId)
//                        .groupBy(TargetSubBaseTable::getSubId));
//        if (ObjectUtil.isNotEmpty(subBaseTables)) {
//            List<List<ResultsTemplate.SubMbInfo>> subList = Lists.newArrayList();
//            for (TargetSubBaseTable subBaseTable : subBaseTables) {
//                List<MbPropertyInfo> subInfo = targetSpecialAttributeMapper.getSubTableInfo(tarId, subBaseTable.getSubId(), subBaseTable.getTargetClassify());
//                Map<String, String> subMap = subInfo.stream().collect(Collectors.toMap(MbPropertyInfo::getName, MbPropertyInfo::getValue));
//                List<ResultsTemplate.SubMbInfo> subProperty = Lists.newArrayList();
//                subProperty.add(ResultsTemplate.SubMbInfo.builder()
//                        .num(1).explain("子MB名称").unit("-").content(subMap.get("子MB名称")).build());
//                subProperty.add(ResultsTemplate.SubMbInfo.builder()
//                        .num(1).explain("子MB类型").unit("-").content(subMap.get("子MB类型")).build());
//                subProperty.add(ResultsTemplate.SubMbInfo.builder()
//                        .num(1).explain("经度").unit("-").content(subMap.get("经度")).build());
//                subProperty.add(ResultsTemplate.SubMbInfo.builder()
//                        .num(1).explain("纬度").unit("-").content(subMap.get("纬度")).build());
//                subProperty.add(ResultsTemplate.SubMbInfo.builder()
//                        .num(1).explain("大地高").unit("-").content(subMap.get("大地高")).build());
//                subProperty.add(ResultsTemplate.SubMbInfo.builder()
//                        .num(1).explain("海拔高").unit("-").content(subMap.get("海拔高")).build());
//                subProperty.add(ResultsTemplate.SubMbInfo.builder()
//                        .num(1).explain("点位误差").unit("-").content(subMap.get("点位误差")).build());
//                subProperty.add(ResultsTemplate.SubMbInfo.builder()
//                        .num(1).explain("纬度误差").unit("-").content(subMap.get("纬度误差")).build());
//                subProperty.add(ResultsTemplate.SubMbInfo.builder()
//                        .num(1).explain("经度误差").unit("-").content(subMap.get("经度误差")).build());
//                subProperty.add(ResultsTemplate.SubMbInfo.builder()
//                        .num(1).explain("大地高误差").unit("-").content(subMap.get("大地高误差")).build());
//                subProperty.add(ResultsTemplate.SubMbInfo.builder()
//                        .num(1).explain("海拔误差").unit("-").content(subMap.get("海拔误差")).build());
//                subProperty.add(ResultsTemplate.SubMbInfo.builder()
//                        .num(1).explain("原图误差").unit("-").content(subMap.get("原图误差")).build());
//                subProperty.add(ResultsTemplate.SubMbInfo.builder()
//                        .num(1).explain("面积").unit("-").content(subMap.get("面积")).build());
//                subProperty.add(ResultsTemplate.SubMbInfo.builder()
//                        .num(1).explain("结构").unit("-").content(subMap.get("结构")).build());
//                subProperty.add(ResultsTemplate.SubMbInfo.builder()
//                        .num(1).explain("子MB形状").unit("-").content(subMap.get("子MB形状")).build());
//                subProperty.add(ResultsTemplate.SubMbInfo.builder()
//                        .num(1).explain("圆内半径").unit("-").content(subMap.get("圆内半径")).build());
//                subProperty.add(ResultsTemplate.SubMbInfo.builder()
//                        .num(1).explain("圆外半径").unit("-").content(subMap.get("圆外半径")).build());
//                subProperty.add(ResultsTemplate.SubMbInfo.builder()
//                        .num(1).explain("矩形长").unit("-").content(subMap.get("矩形长")).build());
//                subProperty.add(ResultsTemplate.SubMbInfo.builder()
//                        .num(1).explain("矩形宽").unit("-").content(subMap.get("矩形宽")).build());
//                subProperty.add(ResultsTemplate.SubMbInfo.builder()
//                        .num(1).explain("矩形长方向夹角").unit("-").content(subMap.get("矩形长方向夹角")).build());
//                subList.add(subProperty);
//            }
//            template.setSubList(subList);
//        }
//        InputStream ins = null;
//        IXDocReport report = null;
//        IContext context = null;
//        try {
//            ins = new FileInputStream("D:\\desktop\\项目\\昆明\\apiBuild\\src\\main\\resources\\template\\成果导出模板.docx");
//            report = XDocReportRegistry.getRegistry().loadReport(ins, TemplateEngineKind.Freemarker);
//            context = report.createContext();
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } catch (XDocReportException e) {
//            e.printStackTrace();
//        }
//        context.put("country", mainTable.getCountry());
//        context.put("mbArea", mainTable.getTarRegion());
//        context.put("mbName", mainTable.getTarName());
//        context.put("mbNum", mainTable.getTarSerial());
//        context.put("mbClass", mainTable.getTarGradient());
//        context.put("mbType", mainTable.getTarType());
//        context.put("subMb", mainTable.getSubPosition());
//        context.put("coordinate", mainTable.getCoordinateSystem());
//        context.put("longitude", mainTable.getLon());
//        context.put("latitude", mainTable.getLat());
//        context.put("earthHeight", mainTable.getGeoHeight());
//        context.put("altitude", mainTable.getAltitude());
//        context.put("time", mainTable.getReorganizeDate());
//        context.put("unit", mainTable.getReorganizeUnit());
//        String fileName = "规划方案导出" + DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN) + ".docx";
//        String fullPath = keyWordSystem.getFILE_URL() + "/file/" + fileName;
//        FileOutputStream out = null;
//        try {
//            out = new FileOutputStream(FileUtil.newFile(fullPath));
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
//        try {
//            report.process(context, out);
//        } catch (XDocReportException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        //复制表格
//        try {
//            WordGrtUtil.copyTableByLoop(fullPath, 1, 0, fullPath);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        //表格赋值
//        try {
//            WordGrtUtil.setTableValue(fullPath, new ArrayList<>());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        try {
//            out.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        try {
//            ins.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return JSON.toJSONString(R.success("导出成功"));
    }

    @Override
    public Result targetList() {
        List<Map<String, Object>> resultList = new ArrayList<>();
        List<TargetBaseData> baseDataList = targetBaseDataMapper.selectList(
                new LambdaQueryWrapper<TargetBaseData>().eq(TargetBaseData::getDeleteSign, 1)
                        .orderByDesc(TargetBaseData::getCreateTime));
        if (CollectionUtil.isNotEmpty(baseDataList)) {
            Map<String, Object> map = null;
            for (TargetBaseData data : baseDataList) {
                map = new HashMap<>();
                map.put("type", "2");
                map.put("typeId", data.getTargetId());
                map.put("typeName", data.getTargetName());
                //子目标
                String redisKey = RedisName.TARGET_SUB_RELATION_LIST + "_" + data.getTargetId();
                if (redisUtil.hasKey(redisKey)) {
                    List<Map<String, Object>> child = new ArrayList<>();
                    Map<String, Object> sub = null;
                    Set<Object> subs = redisUtil.sGet(redisKey);
                    for (Object subId : subs) {
                        sub = new HashMap<>();
                        sub.put("type", "2");
                        sub.put("typeId", subId);
                        sub.put("typeName", redisUtil.hget(RedisName.TARGET_BASE_DATA_ALL + "_" + subId, "targetName"));
                        child.add(sub);
                    }
                    map.put("children", child);
                }
                resultList.add(map);
            }
        }
        return ResultUtil.success(resultList);
    }

    @Override
    public String typeList() {
        List<Map<String, Object>> resultList = new ArrayList<>();
        List<RepacigiBaseTable> baseTables = repacigiBaseTableService
                .lambdaQuery()
                .eq(RepacigiBaseTable::getType, 0)
                .orderByAsc(RepacigiBaseTable::getCreateTime)
                .list();
        baseTables.forEach(base -> {
            if ("0".equals(base.getParentId())) {
                Map<String, Object> map = new HashMap<>();
                map.put("type", "2");
                map.put("typeId", base.getTypeId());
                map.put("typeName", base.getTypeName());
                map.put("children", getRepacigiBaseTree(base.getTypeId(), baseTables));
                resultList.add(map);
            }
        });
//        List<TargetType> list = targetTypeMapper.findAll();
//        List<TargetSubType> subTypes = targetSubTypeMapper.selectList(null);
//        if (CollectionUtil.isNotEmpty(list)) {
//            Map<String, Object> typeMap;
//            for (TargetType targetType : list) {
//                if (targetType.getLevel().equals("1")) {
//                    typeMap = new HashMap<>();
//                    typeMap.put("type", "2");
//                    typeMap.put("typeId", targetType.getTypeId());
//                    typeMap.put("typeName", targetType.getTypeName());
//                    List<Map<String, Object>> child = getTargetAndSubTree(targetType.getTypeId(), list, subTypes);
//                    if (CollectionUtil.isNotEmpty(child)) {
//                        typeMap.put("children", child);
//                    }
//                    resultList.add(typeMap);
//                }
//            }
//        }
        return JSON.toJSONString(R.data(resultList));
    }

    private List<Map<String, Object>> getRepacigiBaseTree(String id, List<RepacigiBaseTable> allTree) {
        /**
         * 子菜单
         */
        List<Map<String, Object>> childList = new ArrayList<>();
        for (RepacigiBaseTable base : allTree) {
            if (id.equals(base.getParentId())) {
                Map<String, Object> map = new HashMap<>();
                map.put("typeId", base.getTypeId());
                map.put("typeName", base.getTypeName());
                map.put("type", "2");
                childList.add(map);
            }
        }
        if (childList.size() == 0) {
            return new ArrayList<>();
        }
        /**
         * 递归
         */
        for (Map<String, Object> map : childList) {
            String typeId = (String) map.get("typeId");
            List<Map<String, Object>> subTree = getRepacigiBaseTree(typeId, allTree);
            map.put("children", subTree);
        }
        return childList;
    }

    private List<Map<String, Object>> getTargetAndSubTree(String id, List<TargetType> allTree, List<TargetSubType> subList) {
        /**
         * 子菜单
         */
        List<Map<String, Object>> childList = new ArrayList<>();
        for (TargetType targetType : allTree) {
            if (id.equals(targetType.getParentId())) {
                Map<String, Object> map = new HashMap<>();
                map.put("typeId", targetType.getTypeId());
                map.put("typeName", targetType.getTypeName());
                map.put("type", "2");
                childList.add(map);
            }
        }
        if (childList.size() == 0) {
            return new ArrayList<>();
        }
        /**
         * 递归
         */
        for (Map<String, Object> map : childList) {
            String typeId = (String) map.get("typeId");
            List<Map<String, Object>> subTree = getTargetAndSubTree(typeId, allTree, subList);
            for (TargetSubType targetSubType : subList) {
                if (targetSubType.getParentId().equals(typeId)) {
                    Map<String, Object> sub = new HashMap<>();
                    sub.put("typeId", targetSubType.getTypeId());
                    sub.put("typeName", targetSubType.getTypeName());
                    sub.put("type", "2");
                    subTree.add(sub);
                }
            }
            map.put("children", subTree);
        }
        return childList;
    }

    @Override
    public Result mbList(JSONObject jsonObject) {
        //jsonobject解析获取类别
        String typeId = jsonObject.getString("typeId");
        //jsonobject解析获取名称
        String country = jsonObject.getString("country");
        //jsonobject解析国家
        String tarName = jsonObject.getString("tarName");
        List<RepacigiBaseTable> baseTables = repacigiBaseTableService.lambdaQuery()
                .eq(RepacigiBaseTable::getParentId, typeId)
                .like(StringUtils.isNotBlank(tarName), RepacigiBaseTable::getTypeName, tarName)
                .eq(RepacigiBaseTable::getType, 1)
                .list();
        List<RepacigiSubTable> subTables = repacigiSubTableService.list();
        List<Map<String, Object>> list = Lists.newArrayList();
        baseTables.forEach(data -> {
            Map<String, Object> map = new HashMap<>();
            map.put("tarId", data.getTypeId());
            map.put("tarName", data.getTypeName());
            map.put("typeId", data.getParentId());
            List<Map<String, Object>> subList = Lists.newArrayList();
            subTables.forEach(sub -> {
                if (data.getTypeId().equals(sub.getTargetId())) {
                    Map<String, Object> subMap = new HashMap<>();
                    subMap.put("subId", sub.getSubId());
                    subMap.put("subName", sub.getSubName());
                    subMap.put("typeId", data.getParentId());
                    subList.add(subMap);
                }
            });
            map.put("children", subList);
            list.add(map);
        });
//        if (StringUtils.isNotBlank(typeId)) {
//            List<TargetData> dataList = targetMapper.findAlls(typeId, tarName);
//            if (CollectionUtil.isNotEmpty(dataList)) {
//                Map<String, Object> target;
//                for (TargetData targetData : dataList) {
//                    target = new HashMap<>();
//                    target.put("tarId", targetData.getTargetId());
//                    target.put("tarName", targetData.getTargetName());
//                    target.put("typeId", targetData.getTargetClassify());
//                    List<Map<String, Object>> subList = Lists.newArrayList();
//                    try {
//                        List<Map<String, Object>> sub = repo.selectTargetSubList(this.keyWordSystem.getFILE_URL() + targetData.getSqliteUrl(), keyWordSystem.getSERVER_URL());
//                        if (CollectionUtil.isNotEmpty(sub)) {
//                            Map<String, Object> subMap;
//                            for (Map<String, Object> map : sub) {
//                                subMap = new HashMap<>();
//                                subMap.put("subId", map.get("subId"));
//                                subMap.put("subName", map.get("targetName"));
//                                subMap.put("typeId", map.get("targetClassify"));
//                                subList.add(subMap);
//                            }
//                        }
//                    } catch (SQLException throwables) {
//                        throwables.printStackTrace();
//                    }
//                    target.put("children", subList);
//                    list.add(target);
//                }
//            }
//        }
        return ResultUtil.success(list);
    }

    @Override
    public Result typeEdit(JSONObject jsonObject) {
        //标识
        String typeId = jsonObject.getString("typeId");
        //名称
        String typeName = jsonObject.getString("typeName");
        if (typeId.equals("0")) {
            String pId = jsonObject.getString("pId");
            if (pId.equals("0")) {
                Integer integer = targetTypeMapper.selectSpecialCount("1");
                if (null == integer) {
                    integer = 1;
                } else {
                    integer++;
                }
                TargetType newType = new TargetType();
                newType.setTypeId(snowflakeIdWorker.nextId() + "");
                newType.setTypeName(typeName);
                newType.setLevel("1");
                newType.setParentId("1");
                newType.setSort(integer);
                if (targetTypeMapper.insert(newType) > 0) {
                    JSONObject result = new JSONObject();
                    result.put("typeId", newType.getTypeId());
                    redisUseService.updateTypeName(newType.getTypeId(), newType.getTypeName());
                    return ResultUtil.success("新增成功", result);
                }
            } else {
                TargetType targetType = targetTypeMapper.selectTypeOnly(pId);
                if (ObjectUtil.isNotEmpty(targetType)) {
                    Integer integer = targetTypeMapper.selectSpecialCount(targetType.getTypeId());
                    if (null == integer) {
                        integer = 1;
                    } else {
                        integer++;
                    }
                    TargetType newType = new TargetType();
                    newType.setTypeId(snowflakeIdWorker.nextId() + "");
                    newType.setTypeName(typeName);
                    newType.setLevel((Integer.valueOf(targetType.getLevel()) + 1) + "");
                    newType.setParentId(targetType.getTypeId());
                    newType.setSort(integer);
                    if (targetTypeMapper.insert(newType) > 0) {
                        JSONObject result = new JSONObject();
                        result.put("typeId", newType.getTypeId());
                        redisUseService.updateTypeName(newType.getTypeId(), newType.getTypeName());
                        return ResultUtil.success("新增成功", result);
                    }
                }
            }
        } else {
            TargetType targetType = new TargetType();
            targetType.setTypeId(typeId);
            targetType.setTypeName(typeName);
            //修改指标主体名称
            systemIndexService.lambdaUpdate()
                    .eq(SystemIndex::getRedId, typeId)
                    .eq(SystemIndex::getParentId, "0")
                    .set(SystemIndex::getIndicatorName, typeName)
                    .update();
            if (targetTypeMapper.updateType(targetType) > 0) {
                redisUseService.updateTypeName(targetType.getTypeId(), targetType.getTypeName());
                return ResultUtil.success("更新成功", null);
            }
        }
        return ResultUtil.error(500, "无数据");
    }

    @Override
    public String postureEdit(JSONObject jsonObject) {
        //标识
        String typeId = jsonObject.getString("typeId");
        //名称
        String typeName = jsonObject.getString("typeName");
        if (typeId.equals("0")) {
            String pId = jsonObject.getString("pId");
            Integer integer = null;
            String level = null;
            String parentId = null;
            if (pId.equals("0")) {
                integer = postureTypeService.getTypeMaxSort("1");
                if (null == integer) {
                    integer = 1;
                } else {
                    integer++;
                }
                level = "1";
                parentId = "1";
            } else {
                PostureType postureType = postureTypeService.getById(pId);
                if (ObjectUtil.isNotEmpty(postureType)) {
                    integer = postureTypeService.getTypeMaxSort(postureType.getTypeId());
                    if (null == integer) {
                        integer = 1;
                    } else {
                        integer++;
                    }
                    level = (Integer.valueOf(postureType.getLevel()) + 1) + "";
                    parentId = postureType.getTypeId();
                } else {
                    return JSON.toJSONString(R.fail("无数据"));
                }
            }
            PostureType postureType = new PostureType();
            postureType.setTypeName(typeName);
            postureType.setLevel(level);
            postureType.setParentId(parentId);
            postureType.setSort(integer);
            if (postureTypeService.save(postureType)) {
                JSONObject result = new JSONObject();
                result.put("typeId", postureType.getTypeId());
                redisUseService.updatePostureTypeName(postureType.getTypeId(), postureType.getTypeName());
                return JSON.toJSONString(R.data(result, "新增成功"));
            }
        } else {
            if (postureTypeService.lambdaUpdate().set(PostureType::getTypeName, typeName).eq(PostureType::getTypeId, typeId).update()) {
                redisUseService.updatePostureTypeName(typeId, typeName);
                return JSON.toJSONString(R.success("更新成功"));
            }
        }
        return JSON.toJSONString(R.fail("无数据"));
    }

    @Override
    public String typeDelete(JSONObject jsonObject) {
        //标识
        String typeId = jsonObject.getString("typeId");
        if ("1".equals(typeId)) {
            return JSON.toJSONString(R.fail("根节点不可被删除"));
        }
        List<String> typeIds = new ArrayList<>();
        typeIds.add(typeId);
        deleteTargetType(typeIds, typeId);
        for (String id : typeIds) {
            targetTypeMapper.delType(id);
            redisUseService.deleteTypeName(id);
            redisUseService.deleteSign(id);
            //删除子类型
            List<TargetSubType> list = targetSubTypeService.lambdaQuery().eq(TargetSubType::getParentId, id).list();
            if (CollectionUtil.isNotEmpty(list)) {
                for (TargetSubType targetSubType : list) {
                    targetSubTypeService.removeById(targetSubType.getTypeId());
                    redisUseService.deleteSubTypeName(targetSubType.getTypeId());
                }
            }
        }
//        if (targetTypeMapper.delType(typeId) > 0) {
//            return JSON.toJSONString(R.success("删除成功"));
//        }
        return JSON.toJSONString(R.success("删除成功"));
    }

    private void deleteTargetType(List<String> typeIds, String typeId) {
        List<TargetType> typeByParantId = targetTypeMapper.findTargetTypeByParantId(typeId);
        if (CollectionUtil.isNotEmpty(typeByParantId)) {
            for (TargetType targetType : typeByParantId) {
                typeIds.add(targetType.getTypeId());
                deleteTargetType(typeIds, targetType.getTypeId());
            }
        }
    }

    @Override
    public String postureDelete(JSONObject jsonObject) {
        //标识
        String typeId = jsonObject.getString("typeId");
        if ("1".equals(typeId)) {
            return JSON.toJSONString(R.fail("根节点不可被删除"));
        }
        if (postureTypeService.removeById(typeId)) {
            redisUseService.deleteSign(typeId);
            redisUseService.deletePostureTypeName(typeId);
            return JSON.toJSONString(R.success("删除成功"));
        }
        return JSON.toJSONString(R.fail("无数据"));
    }

    @Override
    public String subMap(JSONObject jsonObject) {
        //jsonobject解析获取MB标识
        String tarId = jsonObject.getString("tarId");
        //jsonobject解析获取子MB标识
        String subId = jsonObject.getString("subId");
        if (jsonObject == null || jsonObject.size() < 1
        ) {
            return "{\"msg\":\"操作成功\",\"code\":200,\"data\":{},\"success\":true}";
        }
        if (jsonObject == null || jsonObject.size() < 1
        ) {
            return "";
        }
        return JSON.toJSONString(R.success("无数据"));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result tarDelete(JSONObject jsonObject) {
        //jsonobject解析获取标识
        String id = jsonObject.getString("tarId");
        //jsonobject解析获取子MB标识
        String subId = jsonObject.getString("subId");
        if (StringUtils.isBlank(subId)) {
            repacigiBaseTableService.removeById(id);
            repacigiMainTableService.removeById(id);
        } else {
            repacigiSubTableService.removeById(subId);
        }
        return ResultUtil.success("删除成功", null);
    }

    @Override
    public String tarMap(JSONObject jsonObject) {
        //jsonobject解析获取MB标识
        String tarId = jsonObject.getString("tarId");
        TargetPositon targetPositon = targetPositonService.getById(tarId);
        JSONObject json = new JSONObject();
        if (ObjectUtil.isNotEmpty(targetPositon)) {
            json.put("tarId", targetPositon.getTarId());
            json.put("position", targetPositon.getPosition());
            json.put("plotList", targetPositon.getPlotList());
            json.put("outPlot", targetPositon.getOutPlot());
            json.put("tarName", targetPositon.getTarName());
            json.put("tarType", targetPositon.getTarType());
        } else {
            json.put("tarId", tarId);
            json.put("position", "");
            json.put("plotList", "[]");
            json.put("outPlot", "");
            json.put("tarName", "");
            json.put("tarType", "");
        }
        return JSON.toJSONString(R.data(json));
    }

    @Override
    public Result tarEdit(JSONObject jsonObject) {
        //jsonobject解析获取标识
        String tarId = jsonObject.getString("tarId");
        //jsonobject解析获取名称
        String name = jsonObject.getString("name");
        //jsonobject解析获取类型标识
        String subId = jsonObject.getString("subId");
        String typeId = jsonObject.getString("typeId");
        String country = jsonObject.getString("country");
        if (StringUtils.isBlank(tarId)) {
            return ResultUtil.error(500, "目标不存在，请重新选择");
        }
        if (StringUtils.isBlank(name)) {
            return ResultUtil.error(500, "目标/子目标名称不能为空");
        }
        if (null == subId) {
            if ("0".equals(tarId)) {
                if (StringUtils.isBlank(typeId)) {
                    return ResultUtil.error(500, "请选择类型");
                }
                RepacigiBaseTable baseTable = new RepacigiBaseTable();
                baseTable.setParentId(typeId);
                baseTable.setTypeName(name);
                baseTable.setType("1");
                baseTable.setSort(repacigiBaseTableService.lambdaQuery().eq(RepacigiBaseTable::getParentId, typeId).eq(RepacigiBaseTable::getType, 1).count() + 1);
                repacigiBaseTableService.save(baseTable);
                RepacigiMainTable repacigiMainTable = new RepacigiMainTable();
                repacigiMainTable.setTarId(baseTable.getTypeId());
                repacigiMainTable.setTarName(name);
                repacigiMainTableService.save(repacigiMainTable);
            } else {
                RepacigiBaseTable baseTable = repacigiBaseTableService.getById(tarId);
                baseTable.setTypeName(name);
                repacigiBaseTableService.updateById(baseTable);
                RepacigiMainTable mainTable = repacigiMainTableService.getById(tarId);
                if (ObjectUtil.isEmpty(mainTable)) {
                    mainTable = new RepacigiMainTable();
                    mainTable.setTarId(baseTable.getTypeId());
                }
                mainTable.setTarName(name);
                repacigiMainTableService.saveOrUpdate(mainTable);
            }
        } else {
            if ("0".equals(subId)) {
                if (StringUtils.isBlank(typeId)) {
                    return ResultUtil.error(500, "请选择类型");
                }
                RepacigiSubTable subTable = new RepacigiSubTable();
                subTable.setTargetId(tarId);
                subTable.setSubType(typeId);
                subTable.setSubName(name);
                repacigiSubTableService.save(subTable);
            } else {
                RepacigiSubTable subTable = repacigiSubTableService.getById(subId);
                subTable.setSubName(name);
                repacigiSubTableService.updateById(subTable);
            }
        }
//        if ("0".equals(tarId)) {
//            TargetData targetData = new TargetData();
//            ExternalTarget externalTarget = new ExternalTarget();
//            //新增目标
//            try {
//                externalTarget.setTargetId(snowflakeIdWorker.nextId() + "");
//                externalTarget.setTargetName(name);
//                externalTarget.setType(typeId);
//                externalTarget.setCountry(country);
//                externalTarget.setLon(0.0);
//                externalTarget.setLat(0.0);
//                String sqliteUrl = "/local/" + externalTarget.getTargetId() + ".db";
//                List<com.xinchuang.sqlite.entity.TargetData> list = FileElseUtil.getSqliteTarget(externalTarget);
//                List<CommonAttribute> commons = commonMapper.findCommons(1);
//                if (CollectionUtil.isNotEmpty(commons)) {
//                    for (CommonAttribute common : commons) {
//                        if ("desicribe".equals(common.getKey())) {
//                            continue;
//                        }
//                        com.xinchuang.sqlite.entity.TargetData data = new com.xinchuang.sqlite.entity.TargetData();
//                        data.setId(snowflakeIdWorker.nextId() + "");
//                        data.setKey(common.getKey());
//                        data.setKeyName(common.getKeyName());
//                        data.setKeyType(common.getKeyType());
//                        data.setKeyValue("");
//                        data.setRemark("");
//                        data.setPerson("main-system");
//                        data.setSource("api-port");
//                        list.add(data);
//                    }
//                }
//                targetRepo.addTargetList(this.keyWordSystem.getFILE_URL() + sqliteUrl, list);
//                targetData.setSqliteUrl(sqliteUrl);
//            } catch (SQLException sqlException) {
//                return JSON.toJSONString(R.fail(500, "数据异常稍后重试"));
//            }
//            targetData.setTargetId(externalTarget.getTargetId());
//            targetData.setTargetName(externalTarget.getTargetName());
//            targetData.setLon(externalTarget.getLon());
//            targetData.setLat(externalTarget.getLat());
//            targetData.setCountry(externalTarget.getCountry());
//            targetData.setTargetClassify(typeId);
//            targetData.setHeight(0D);
//            targetData.setDeleteSign(1);
//            target.addTarget(targetData);
//            RepacigiMainTable build = RepacigiMainTable.builder().tarId(externalTarget.getTargetId()).tarName(name).build();
//            repacigiMainTableService.saveOrUpdate(build);
//            JSONObject result = new JSONObject();
//            result.put("tarId", externalTarget.getTargetId());
//            return JSON.toJSONString(R.data(result, "新增目标成功"));
//        } else if (!"0".equals(tarId) && "0".equals(subId)) {
//            TargetData targetData = targetMapper.findTargetOnly(tarId);
//            if (null == targetData || targetData.getDeleteSign() == 0) {
//                return JSON.toJSONString(R.fail(500, "目标已删除/不存在"));
//            }
//            String s = repo.selectSubName(this.keyWordSystem.getFILE_URL() + targetData.getSqliteUrl(), name);
//            if (StringUtils.isNotBlank(s)) {
//                return JSON.toJSONString(R.fail(404, "子目标名称重复，请重新填写"));
//            }
//            subId = snowflakeIdWorker.nextId() + "";
//            repo.addTargetSubMessage(this.keyWordSystem.getFILE_URL() + targetData.getSqliteUrl(), subId, FileElseUtil.getSubTarget(subId, name), "");
//            RepacigiSubTable build = RepacigiSubTable.builder().subId(subId).targetId(tarId).subName(name).build();
//            repacigiSubTableService.saveOrUpdate(build);
//            JSONObject result = new JSONObject();
//            result.put("subId", subId);
//            return JSON.toJSONString(R.data(subId, "新增子目标成功"));
//        } else {
//            TargetData targetOnly = targetMapper.findTargetOnly(tarId);
//            if (ObjectUtil.isNotEmpty(targetOnly)) {
//                if (StringUtils.isBlank(subId)) {
//                    try {
//                        repo.updateTableKeyAndKeyValue(keyWordSystem.getFILE_URL() + targetOnly.getSqliteUrl(), tarId, null, "targetName", name);
//                        TargetData target = new TargetData();
//                        target.setTargetId(tarId);
//                        target.setTargetName(name);
//                        targetMapper.update(target);
//                        RepacigiMainTable build = RepacigiMainTable.builder().tarId(tarId).tarName(name).build();
//                        repacigiMainTableService.saveOrUpdate(build);
//                    } catch (SQLException throwables) {
//                        throwables.printStackTrace();
//                    }
//                } else {
//                    try {
//                        repo.updateTableKeyAndKeyValue(keyWordSystem.getFILE_URL() + targetOnly.getSqliteUrl(), tarId, subId, "targetName", name);
//                        RepacigiSubTable build = RepacigiSubTable.builder().subId(subId).targetId(tarId).subName(name).build();
//                        repacigiSubTableService.saveOrUpdate(build);
//                    } catch (SQLException throwables) {
//                        throwables.printStackTrace();
//                    }
//                }
//                return JSON.toJSONString(R.success("编辑成功"));
//            }
//        }
        return ResultUtil.success();
    }

    public boolean updateTargetOrSubName(String targetId, String subId, String name) {
        TargetData targetOnly = targetMapper.findTargetOnly(targetId);
        if (ObjectUtil.isNotEmpty(targetOnly)) {
            if (StringUtils.isBlank(subId)) {
                try {
                    repo.updateTableKeyAndKeyValue(keyWordSystem.getFILE_URL() + targetOnly.getSqliteUrl(), targetId, null, "targetName", name);
                    TargetData target = new TargetData();
                    target.setTargetId(targetId);
                    target.setTargetName(name);
                    targetMapper.update(target);
                    RepacigiMainTable build = RepacigiMainTable.builder().tarId(targetId).tarName(name).build();
                    repacigiMainTableService.saveOrUpdate(build);
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            } else {
                try {
                    String s = repo.selectSubName(this.keyWordSystem.getFILE_URL() + targetOnly.getSqliteUrl(), name);
                    if (StringUtils.isNotBlank(s) && !subId.equals(s)) {
                        return false;
                    }
                    repo.updateTableKeyAndKeyValue(keyWordSystem.getFILE_URL() + targetOnly.getSqliteUrl(), targetId, subId, "targetName", name);
                    RepacigiSubTable build = RepacigiSubTable.builder().subId(subId).targetId(targetId).subName(name).build();
                    repacigiSubTableService.saveOrUpdate(build);
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            return true;
        }
        return false;
    }

    @Override
    public String eleList() {
        List<Ele> list = eleService.list();
        List<Map<String, Object>> resultList = Lists.newArrayList();
        if (CollectionUtil.isNotEmpty(list)) {
            Map<String, Object> map;
            for (Ele ele : list) {
                map = new HashMap<>();
                map.put("eleId", ele.getEleId());
                map.put("eleName", ele.getEleName());
                resultList.add(map);
            }
        }
        return JSON.toJSONString(R.data(resultList));
    }

    @Override
    public String tarMapEdit(JSONObject jsonObject) {
        //jsonobject解析获取标识
        String tarId = jsonObject.getString("tarId");
        //jsonobject解析获取位置
        String position = jsonObject.getString("position");
        //jsonobject解析获取标绘信息
        String plotList = jsonObject.getString("plotList");
        //jsonobject解析获取标绘列表
        String outPlot = jsonObject.getString("outPlot");
        //jsonobject解析获取名称
        String tarName = jsonObject.getString("tarName");
        //jsonobject解析获取类型
        String tarType = jsonObject.getString("tarType");
        TargetPositon targetPositon = new TargetPositon();
        targetPositon.setTarId(tarId);
        targetPositon.setPosition(position);
        targetPositon.setPlotList(plotList);
        targetPositon.setOutPlot(outPlot);
        targetPositon.setTarName(tarName);
        targetPositon.setTarType(tarType);
        targetPositonService.saveOrUpdate(targetPositon);
        return JSON.toJSONString(R.success("无数据"));
    }

    @Override
    public synchronized String upNode(JSONObject jsonObject) {
        //jsonobject解析获取类型
        /**
         * 1,上移同级顶部；
         * 2，上移；
         * 3，下移；
         * 4，下移同级底部
         */
        String type = jsonObject.getString("type");
        String typeId = jsonObject.getString("typeId");
        TargetType targetType = targetTypeMapper.selectTypeOnly(typeId);
        if (null == targetType) {
            JSON.toJSONString(R.fail(404, "类型不存在/已被删除"));
        }
        if (targetType.getParentId().equals("0")) {
            JSON.toJSONString(R.fail(500, "根目录不能移动"));
        }
        TargetType changeType;
        if ("1".equals(type)) {
            Map<String, Object> minType = targetTypeMapper.getMinType(targetType.getLevel());
            if (null != minType) {
                if (targetType.getTypeId().equals(minType.get("id").toString())) {
                    return JSON.toJSONString(R.fail(500, "已经到顶了，不能上移了。"));
                } else {
                    targetTypeMapper.updateTypeSort(targetType.getTypeId(),
                            Integer.valueOf(minType.get("sort").toString()) - 1);
                    return JSON.toJSONString(R.success("操作成功"));
                }
            }
        } else if ("2".equals(type)) {
            changeType = targetTypeMapper.selectUpTargetType(typeId, targetType.getParentId());
            if (null == changeType) {
                return JSON.toJSONString(R.fail(500, "已经到顶了，不能上移了。"));
            }
            targetTypeMapper.updateTypeSort(targetType.getTypeId(), changeType.getSort());
            targetTypeMapper.updateTypeSort(changeType.getTypeId(), targetType.getSort());
            return JSON.toJSONString(R.success("操作成功"));
        } else if ("3".equals(type)) {
            changeType = targetTypeMapper.selectDownTargetType(typeId, targetType.getParentId());
            if (null == changeType) {
                return JSON.toJSONString(R.fail(500, "已经置底了，不能下移了。"));
            }
            targetTypeMapper.updateTypeSort(targetType.getTypeId(), changeType.getSort());
            targetTypeMapper.updateTypeSort(changeType.getTypeId(), targetType.getSort());
            return JSON.toJSONString(R.success("操作成功"));
        } else if ("4".equals(type)) {
            Map<String, Object> minType = targetTypeMapper.getMaxType(targetType.getLevel());
            if (null != minType) {
                if (targetType.getTypeId().equals(minType.get("id").toString())) {
                    return JSON.toJSONString(R.fail(500, "已经置底了，不能下移了。"));
                } else {
                    targetTypeMapper.updateTypeSort(targetType.getTypeId(),
                            Integer.valueOf(minType.get("sort").toString()) + 1);
                    return JSON.toJSONString(R.success("操作成功"));
                }
            }
        }
        return JSON.toJSONString(R.success("无数据"));
    }

    @Override
    public String upPosture(JSONObject jsonObject) {
        Integer sign = jsonObject.getInteger("type");
        String id = jsonObject.getString("typeId");
        PostureType postureType = postureTypeService.getById(id);
        if (cn.hutool.core.util.ObjectUtil.isNotNull(postureType)) {
            if (sign == 1 || sign == 2) {
                if (postureType.getSort() == 1) {
                    return JSON.toJSONString(R.fail(500, "已经上移到最顶"));
                } else if (sign == 1) {
                    postureTypeService.updateSortBetweenAdd(postureType.getParentId(), 1, postureType.getSort() - 1);
                    postureType.setSort(1);
                    postureTypeService.updateById(postureType);
                } else {
                    postureTypeService.updateSortBetweenAdd(postureType.getParentId(), postureType.getSort() - 1, postureType.getSort() - 1);
                    postureType.setSort(postureType.getSort() - 1);
                    postureTypeService.updateById(postureType);
                }
                return JSON.toJSONString(R.success("操作成功"));
            } else {
                Integer maxSort = postureTypeService.getTypeMaxSort(postureType.getParentId());
                if (null != maxSort && maxSort.intValue() == postureType.getSort()) {
                    return JSON.toJSONString(R.fail(500, "已经下移到最底"));
                } else if (sign == 3) {
                    postureTypeService.updateSortBetweenSub(postureType.getParentId(), postureType.getSort() + 1, postureType.getSort() + 1);
                    postureType.setSort(postureType.getSort() + 1);
                    postureTypeService.updateById(postureType);
                } else {
                    postureTypeService.updateSortBetweenSub(postureType.getParentId(), postureType.getSort() + 1, maxSort);
                    postureType.setSort(maxSort);
                    postureTypeService.updateById(postureType);
                }
                return JSON.toJSONString(R.success("操作成功"));
            }
        }
        return JSON.toJSONString(R.success("无数据"));
    }

}
